import Vue from 'vue'
import VueRouter from 'vue-router'

// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import store from '@/store/index'
import util from '@/libs/util.js'
import routes, { constantRoutes } from '@/router/routes'

// 路由数据
// import { constantRoutes } from './routes'
import { generateMenuHeaderByRoutes } from '@/menu'

// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return VueRouterPush.call(this, location).catch(err => err)
}
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
  return VueRouterReplace.call(this, location).catch(err => err)
}
console.log('routes', routes)

Vue.use(VueRouter)
const createRouter = () =>
  new VueRouter({
    // mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes
  })

// 导出路由 在 main.js 里使用
const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter (router) {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach(async (to, from, next) => {
  // 确认已经加载多标签页数据 https://github.com/d2-projects/d2-admin/issues/201
  await store.dispatch('page/isLoaded')
  // 确认已经加载组件尺寸设置 https://github.com/d2-projects/d2-admin/issues/198
  await store.dispatch('size/isLoaded')
  // 进度条
  NProgress.start()
  // 关闭搜索面板
  store.commit('search/set', false)
  // 验证当前路由所有的匹配中是否需要有登录验证的
  if (to.matched.some(r => r.meta.auth)) {
    // 这里暂时将cookie里是否存有token作为验证是否登录的条件
    // 请根据自身业务需要修改
    const token = util.cookies.get('token')
    if (token && token !== 'undefined') {
      // 加载用户角色信息
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (!hasRoles) {
        store.dispatch('account/getRoles')

        // 加载路由
        const accessRoutes = await store.dispatch('permission/dynamicGenerateRoutes')
        if (router.matcher.length > 1) {
          resetRouter(router)
        }
        router.addRoutes(accessRoutes)

        // 把路由转换成菜单
        const menuHeader = generateMenuHeaderByRoutes(constantRoutes.concat(accessRoutes))
        // 设置顶栏菜单
        store.commit('menu/headerSet', menuHeader)
        // 初始化菜单搜索功能
        store.commit('search/init', menuHeader)

        // 刷新了后, 需要用nextTo才能跳转, next 会找不到路由
        next({ ...to, replace: true })
        return
      }

      next()
    } else {
      // 没有登录的时候跳转到登录界面
      // 携带上登陆成功之后需要跳转的页面完整路径
      next({
        name: 'login',
        query: {
          redirect: to.fullPath
        }
      })
      // https://github.com/d2-projects/d2-admin/issues/138
      NProgress.done()
    }
  } else {
    // 不需要身份校验 直接通过
    next()
  }
})

router.afterEach(to => {
  // 进度条
  NProgress.done()
  // 多页控制 打开新的页面
  store.dispatch('page/open', to)
  // 更改标题
  util.title(to.meta.title)
})

export default router
